package com.huangsm.juc.threadpool;


import sun.print.SunMinMaxPage;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 一、线程池:提供了一个线程队列，队列中保存着所有等待状态的线程。变量了创建于销毁额外的开销，提高了响应的速度
 * <p>
 * 二、线程池的体系结构
 * java.util.concurrent.Executor:负责线程的使用与调度的跟接口
 * |--ExecutorService:自接口:线程池的主要接口
 * |--ThreadPoolExecutor 实现类
 * |--ScheduleExecutorService 子接口：负责线程的调度
 * |--ScheduledThreadPoolExecutor: 继承ThreadPoolExecutor实现ScheduleExecutorService，具备线程池和线程调度的功能
 * <p>
 * 三、工具类:Executors
 * ExecutorService newFixedThreadPool()：创建固定大小的线程池
 * ExecutorService newCachedThreadPool()：缓存线程池，线程池的数量不固定，可以根据需求自动的更改数量
 * ExecutorService newSingleThreadExecutor()：创建单个线程池。线程池中只有一个线程
 * <p>
 * ScheduledExecutorService newScheduledThreadPool(): 创建固定大小的线程，可以延迟或定时的执行任务
 */
public class ThreadPoolTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        List<Future<Integer>> list=new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future<Integer> submit = executorService.submit(new Callable<Integer>() {
                    @Override
                    public Integer call() throws Exception {
                        int sum = 0;
                        for (int i = 0; i < 20; i++) {
                            sum += i;
                        }
                        return sum;
                    }
                }
            );
            list.add(submit);
        }
        executorService.shutdown();
        list.forEach(f->{
            try {
                System.out.println(f.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
        /*ThreadPoolDemo threadPoolDemo = new ThreadPoolDemo();
        executorService.submit(threadPoolDemo);
        executorService.shutdown();*/
    }
}

class ThreadPoolDemo implements Runnable {

    private int i = 0;

    @Override
    public void run() {
        while (i <= 100) {
            System.out.println(Thread.currentThread().getName() + ":" + i++);
        }
    }
}